package com.samnative.pineapple.main;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.samnative.pineapple.adapter.XuanzeCityLeftAdapter;
import com.samnative.pineapple.adapter.XuanzeCityRightAdapter;
import com.samnative.pineapple.entity.City;
import com.samnative.pineapple.entity.Province;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AmapLocation;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.utils.FileUtils;
import com.samnative.pineapple.utils.GsonUtils;
import com.samnative.pineapple.value.Config;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * 城市切换
 */
public class ChangeCityt2Activity extends BaseActivity implements OnClickListener, EasyPermissions.PermissionCallbacks {


    /**
     * 左边省市区列表
     */
    private List<Province> listProvince;
    /**
     * 左边列表
     */
    private RecyclerView rv_left;
    /**
     * 左边列表
     */
    private XuanzeCityLeftAdapter xuanzeCityLeftAdapter;


    /**
     * 右边城市选择列表
     */
    private RecyclerView rv_right;
    /**
     * 右边列表适配器
     */
    private XuanzeCityRightAdapter xuanzeCityRightAdapter;
    /**
     * 最近记录缓存
     */
    private List<String> zuijinJilu;
    /**
     * 最近访问记录
     */
    private XuanzeCityRightAdapter zuijinJiluAdapter;
    /**
     * 最近访问记录
     */
    private RecyclerView lv_jilu;
    /**
     * 最近记录标题
     */
    private TextView tv_zuijin;

    /**
     * 精选城市，有接口获取，选择推荐的时候会显示
     */
    private List<City> listJingxuan, allCitys;

    /**
     * 显示当前选择的城市
     */
    private TextView tv_dingwei;
    /**
     * 定位和记录模块
     */
    private LinearLayout ll_dingwei;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_change_city2;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        if (allCitys == null) {
            String json = getFromAssets("city.json");
            if (json.length() > 1) {
                allCitys = GsonUtils.fromJsonList(json,
                        new TypeToken<List<City>>() {
                        }.getType());
            }
        }

        find(R.id.tv_back).setOnClickListener(this);
        ll_dingwei = find(R.id.ll_dingwei);
        tv_dingwei = find(R.id.tv_dingwei);
        tv_dingwei.setOnClickListener(this);

        if (!Config.currentCity.isEmpty()) {
            tv_dingwei.setText(Config.currentCity);
        } else {
            tv_dingwei.setText("定位中...");
        }

        if (!EasyPermissions.hasPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
            //申请定位权限
            EasyPermissions.requestPermissions(this, "\"" + getString(R.string.app_name) + "\"需要获取你的当前定位,请确认",
                    110, Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            //开启定位功能
            AmapLocation.getInstance(mContext).startLocation();
        }

        initLeftData();
        initRightData();
        requestData();
    }


    /**
     * 初始化左边数据
     */
    public void initLeftData() {

        listProvince = new ArrayList<>();
        String json = getFromAssets("area.json");
        if (json.length() > 1) {
            listProvince = GsonUtils.fromJsonList(json,
                    new TypeToken<List<Province>>() {
                    }.getType());
        }

        xuanzeCityLeftAdapter = new XuanzeCityLeftAdapter(R.layout.item_xuanzecity_left);
        xuanzeCityLeftAdapter.getData().clear();

        {
            Province province = new Province();
            province.setId(-1);
            province.setName("推荐");
            xuanzeCityLeftAdapter.addData(province);
        }
        {
            Province province = new Province();
            province.setId(-2);
            province.setName("全部城市");
            xuanzeCityLeftAdapter.addData(province);
        }
        xuanzeCityLeftAdapter.addData(listProvince);
        xuanzeCityLeftAdapter.setCurrentIndex(0);
        xuanzeCityLeftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                xuanzeCityLeftAdapter.setCurrentIndex(position);
                if (position == 0) {
                    //显示定位以及最近记录
                    ll_dingwei.setVisibility(View.VISIBLE);
                    xuanzeCityRightAdapter.getData().clear();
                    xuanzeCityRightAdapter.addData(listJingxuan);
                } else {
                    //不显示定位以及最近记录
                    ll_dingwei.setVisibility(View.GONE);
                }

                if (position == 1) {
                    //显示全部城市
                    xuanzeCityRightAdapter.getData().clear();
                    xuanzeCityRightAdapter.addData(allCitys);
                }

                if (position > 1) {
                    //显示各个省下的城市
                    List<City> citys = xuanzeCityLeftAdapter.getData().get(position).getArea();
                    xuanzeCityRightAdapter.getData().clear();
                    xuanzeCityRightAdapter.addData(citys);
                }
            }
        });

        rv_left = find(R.id.rv_left);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_left.setLayoutManager(linearLayoutManager);
        rv_left.setAdapter(xuanzeCityLeftAdapter);
    }

    /**
     * 初始化右边
     */
    private void initRightData() {
        zuijinJilu = new ArrayList<>();
        listJingxuan = new ArrayList<>();
        tv_zuijin = find(R.id.tv_zuijin);


        zuijinJiluAdapter = new XuanzeCityRightAdapter(R.layout.item_xuanzecity_right);
        zuijinJiluAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {


                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCity, zuijinJiluAdapter.getData().get(position)
                                .getName());
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCityCode, zuijinJiluAdapter.getData().get(position).getId() + "");

                saveHistoryData(zuijinJiluAdapter.getData().get(position).getId() + "," + zuijinJiluAdapter.getData().get(position)
                        .getName());

                finish();


            }
        });

        lv_jilu = find(R.id.lv_jilu);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        lv_jilu.setLayoutManager(gridLayoutManager);
        lv_jilu.setAdapter(zuijinJiluAdapter);

        getSearchHistory();

        xuanzeCityRightAdapter = new XuanzeCityRightAdapter(R.layout.item_xuanzecity_right);
        xuanzeCityRightAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCity, xuanzeCityRightAdapter.getData().get(position)
                                .getName());
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCityCode, xuanzeCityRightAdapter.getData().get(position).getId() + "");

                saveHistoryData(xuanzeCityRightAdapter.getData().get(position).getId() + "," + xuanzeCityRightAdapter.getData().get(position)
                        .getName());

                finish();
            }
        });
        rv_right = find(R.id.rv_right);
        GridLayoutManager gridLayoutManager2 = new GridLayoutManager(mContext, 3);
        gridLayoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        rv_right.setLayoutManager(gridLayoutManager2);
        rv_right.setAdapter(xuanzeCityRightAdapter);

    }


    /**
     * 请求数据
     */
    public void requestData() {

        Map<String, String> map = new HashMap<>();
        map.put("_apiname", "stobusiness.index.getCity");
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.post(this, "", map, new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONObject jsonData = result
                            .getJSONObject("data");
                    JSONArray jsonArrHot = jsonData.getJSONArray("hot");
                    listJingxuan = GsonUtils.fromJsonList(
                            jsonArrHot.toString(),
                            new TypeToken<List<City>>() {
                            }.getType());

                    if (xuanzeCityLeftAdapter.getCurrentIndex() == 0) {
                        xuanzeCityRightAdapter.getData().clear();
                        xuanzeCityRightAdapter.addData(listJingxuan);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
            }

            @Override
            public void requestFinish() {
                super.requestFinish();
            }
        });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_dingwei:
                if (Config.currentCity.isEmpty()) {
                    return;
                }


                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCity, Config.currentCity);
                AppPrefer.getInstance(mContext).put(
                        AppPrefer.currentCityCode, Config.currentCityid);
                saveHistoryData(Config.currentCityid + "," + Config.currentCity);
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 读取本地
     *
     * @param fileName
     * @return
     */
    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(
                    getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 将储存最近记录的缓存，转换为显示列表
     *
     * @param jilu
     * @return
     */
    private List<City> jiluToList(List<String> jilu) {
        List<City> zuijin = new ArrayList<>();
        for (int i = 0; i < jilu.size(); i++) {
            String[] str = jilu.get(i).split(",");

            int in = 0;
            try {
                in = Integer.parseInt(str[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }

            City city = new City(in, str[1]);
            zuijin.add(city);
        }
        return zuijin;

    }


    /**
     * 获取搜索历史
     */
    public void getSearchHistory() {
        try {
            File file = new File(FileUtils.getCacheFile(mContext) + Config.HOME_CACHE_PATH
                    + "/xuanzecity_jilu");
            if (file.exists()) {
                List<String> historys = FileUtils.readFileToList(
                        file.getPath(), "UTF-8");
                zuijinJilu.clear();
                zuijinJilu.addAll(historys);
            } else {
                zuijinJilu.clear();
            }
        } catch (Exception e) {
            // TODO: handle exception
            zuijinJilu.clear();
        }
        if (zuijinJilu.size() == 0) {
            tv_zuijin.setVisibility(View.GONE);
            lv_jilu.setVisibility(View.GONE);
        } else {
            tv_zuijin.setVisibility(View.VISIBLE);
            lv_jilu.setVisibility(View.VISIBLE);
            zuijinJiluAdapter.getData().clear();
            zuijinJiluAdapter.addData(jiluToList(zuijinJilu));
        }
    }

    /**
     * 储存添加搜索历史记录
     *
     * @param content
     */
    public void saveHistoryData(String content) {
        for (int i = 0; i < zuijinJilu.size(); i++) {
            if (zuijinJilu.get(i).equals(content)) {
                zuijinJilu.remove(i);
            }
        }

        if (zuijinJilu.size() > 29) {
            List<String> temp = new ArrayList<String>();
            temp.addAll(zuijinJilu.subList(0, 29));
            zuijinJilu.clear();
            zuijinJilu.addAll(temp);
        }

        zuijinJilu.add(0, content);
        FileUtils.writeFile(FileUtils.getCacheFile(mContext) + Config.HOME_CACHE_PATH
                + "/xuanzecity_jilu", zuijinJilu);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
        AmapLocation.getInstance(mContext).stopLocation();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == 110) {
            //开启定位功能
            AmapLocation.getInstance(mContext).startLocation();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }
}
